<template>
  <div class="search-suggestion">
    <van-cell
    v-for="(item,index) in suggestions"
    :key="index"
    @click="$emit('search',item)"
    icon="search">
    <template #title>
      <div v-html="highlight(item)"></div>
    </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'searchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    // 监听输入框内容的改变
    searchText: {
      handler: debounce(function(value) {
        this.loadSearchSuggestion(value)
      }, 500),
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
        // console.log(data);
      } catch (error) {
        this.$toast('请求联想数据失败！')
      }
    },
    highlight(item) {
      const highlightStr = `<span style="color:red;">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, highlightStr)
    }
  }
}
</script>

<style lang="less" scoped></style>
